package com.yj.springbootdesign.observe.demo01;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察目标
 */
public class Subject {

    //观察者集合
    private List<Observer> observers = new ArrayList<>();

    //添加观察者
    public void add(Observer observer){
        observers.add(observer);
    }

    //删除观察者
    public void delete(Observer observer){
        observers.remove(observer);
    }

    //通知所有的观察者
    public void notifyAllObservers(Subject subject){
        for (Observer o : observers) {
            o.update(subject);
        }
    }

    public static void main(String[] args) {
        // 创建主题对象
        ConcreteSubject concreteSubject = new ConcreteSubject();
        // 创建观察者对象
        ConcreteObserver concreteObserver = new ConcreteObserver();
        concreteSubject.add(concreteObserver);
        concreteSubject.change();
    }

}

/**
 * 具体的观察目标对象
 */
class ConcreteSubject extends Subject{

    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public void change(){
        this.setState("具体观察者对象发生改变！");
        this.notifyAllObservers(this);
    }

}

/**
 * 观察者对象
 */
interface Observer{
    void update(Subject subject);
}

/**
 * 具体的观察者
 */
class ConcreteObserver implements Observer{

    @Override
    public void update(Subject subject) {
        System.out.println(((ConcreteSubject)subject).getState());
    }
}